<template>
  <view class="patrolInspect">
    <van-sticky>
      <nav-bar title="巡查巡检" leftArrow>
        <template #right>
          <van-icon @click="goLink('created')" name="add-o" size="25" />
        </template>
      </nav-bar>
      <van-tabs v-model:active="active" offset-top="92rpx" @click="tabClick">
        <van-tab v-for="tab in tabList" :title="tab.title" :name="tab.value"></van-tab>
      </van-tabs>
      <list-calendar v-if="active === 0" :active="active" :dateList="dateList" :poppable="false" :showTitle="false" @getList="getPatrolInspectListByDate"></list-calendar>
    </van-sticky>

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        :finished-text="list.length ? '没有更多了' : ''"
        @load="onLoad"
        class="universal-list-list"
      >
        <template v-if="list.length > 0">
          <van-cell v-for="item in list" :key="item">
            <view class="universal-list-item" @click="goLink('detail',item)">
              <view class="universal-list-head">
                <view class="universal-list-title">{{ item.lineName }}</view>
                <view class="universal-list-status">
                  <van-tag :type="item.dangerFlag.value === '0' ? 'primary' : 'warning'">{{ item.dangerFlag.label }}</van-tag>
                </view>
              </view>
              <view class="universal-list-main">
                <view class="universal-list-detail">
                  <view class="universal-list-detail-title">路线类别：</view>
                  <van-text-ellipsis class="universal-list-detail-cont" :content="item.lineName" />
                </view>
                <view class="universal-list-detail w-full">
                  <view class="universal-list-detail-title">所属工程：</view>
                  <van-text-ellipsis class="universal-list-detail-cont" :content="item?.projectItems || '-'" />
                </view>
                <template v-if="active === 0">
                  <view class="universal-list-detail">
                    <view class="universal-list-detail-title">巡查人员：</view>
                    <van-text-ellipsis class="universal-list-detail-cont" :content="item.checker || '-'" />
                  </view>
                  <view class="universal-list-detail">
                    <view class="universal-list-detail-title">巡查次数：</view>
                    <van-text-ellipsis class="universal-list-detail-cont" :content="(item.checkCount || '0') + '次'" />
                  </view>
                  <view class="universal-list-detail">
                    <view class="universal-list-detail-title">点位数：</view>
                    <van-text-ellipsis class="universal-list-detail-cont" :content="String(item.pointCount)" />
                  </view>
                  <!-- <view class="universal-list-detail w-full">
                    <view class="universal-list-detail-title">开始时间：</view>
                    <van-text-ellipsis class="universal-list-detail-cont" :content="item.startTime" />
                  </view>
                  <view class="universal-list-detail w-full">
                    <view class="universal-list-detail-title">结束时间：</view>
                    <van-text-ellipsis class="universal-list-detail-cont" :content="item.endTime" />
                  </view> -->
                </template>

                <view v-if="active === 1" class="universal-list-detail w-full">
                  <view class="universal-list-detail-title">最新巡检：</view>
                  <van-text-ellipsis class="universal-list-detail-cont" :content="item.lastCheckTime" />
                </view>
              </view>
              <view class="universal-list-footer">
                <view class="universal-list-footer-button">
                  详情<van-icon name="arrow" />
                </view>
              </view>
            </view>
          </van-cell>
        </template>
        <van-empty v-if="!list.length && !loading" description="暂无数据" />
      </van-list>
    </van-pull-refresh>
    <list-calendar v-model:show="show" :active="active" :line="activeLine" :dateList="dateListByLine" :poppable="true" :showTitle="true"></list-calendar>
  </view>
</template>

<script setup>
  import listCalendar from './components/list-calendar'

  import dayjs from 'dayjs';
  import { ref, onBeforeUpdate } from 'vue';
  import { apiPatrolInspectDateByMonth, apiPatrolInspectListByDate, apiPatrolInspectListByLine, apiPatrolInspectDateByLine } from '@/api/patrolInspect';
  import store from '@/store'
  const userInfo = store.getters.GET_USER_INFO.sysUser;

  const active = ref(0);
  const tabList = [
    {
      title: '按日期',
      value: 0,
    },
    {
      title: '按路线',
      value: 1,
    },
  ];
  
  let dateList = ref([]);
  let dateListByLine = ref([]);

  let list = ref([]);
  const activeLine = ref({});
  const activeDate = ref('');
  let pages = {
    pageNum: 1,
    pageSize: 10,
  };
  let totalPages = {};
  const refreshing = ref(false);
  const loading = ref(false);
  const finished = ref(false);

  let show = ref(false);

  const onLoad = () => { 
    tabClick();
  };
  const onRefresh = () => { 
    onLoad();
  };

  const goLink = (type, options) => {
    if (type === 'created') {
      uni.navigateTo({ url: '/pages/patrolInspect/created' })
    } else {
      if (active.value === 0) {
        // 保存线路详情
        store.commit('SET_PATROL_LINE_DETAIL', options);
        // 按日期查询时直接跳转到详情页
        uni.navigateTo({ url: `/pages/patrolInspect/record?id=${options.lineId}&date=${activeDate.value}` })
      } else if (active.value === 1) {
        activeLine.value = options
        getPatrolInspectDateByLine(options.lineId);
        // 按路线查询时弹出日历
        show.value = true;
      }
    }
  };
  const tabClick = () => {
    loading.value = false;
    finished.value = true;
    console.log(111);
    list.value = [];
    if (active.value === 0) {
      getPatrolInspectListByDate();
    } else {
      getPatrolInspectListByLine();
    }
  };

  // 获取当前月巡检日期
  const getPatrolInspectDateByMonth = (month) => {
    const paramsMonth = month || dayjs(new Date()).format('YYYY-MM')
    apiPatrolInspectDateByMonth({
      month: paramsMonth
    }).then(res => {
      dateList.value = res;
    })
  }

  // 按日期获取巡检列表数据
  const getPatrolInspectListByDate = (date) => {
    loading.value = false;
    finished.value = true; // 数据请求中的时候停止再次请求数据
    activeDate.value = date || dayjs(new Date()).format('YYYY-MM-DD');
    apiPatrolInspectListByDate({
      date: activeDate.value,
      userId: userInfo.userId
    }).then(res => {
      list.value = res;
      refreshing.value = false;
    })
  }

  // 按路线获取巡检列表数据
  const getPatrolInspectListByLine = () => {
    loading.value = false;
    finished.value = true; // 数据请求中的时候停止再次请求数据
    apiPatrolInspectListByLine({
      ...pages,
      userId: userInfo.userId
    }).then(res => {
      setList(res);
      // list.value = res.data;
    })
  }

  // 获取当前路线巡检日期
  const getPatrolInspectDateByLine = (id) => {
    apiPatrolInspectDateByLine({
      lineId: id,
      userId: userInfo.userId
    }).then(res => {
      dateListByLine.value = res
    })
  }

  const setList = (res) => {
    // 如果是第一页,列表数据清空
    if (res.current === '1') {
      list.value = [];
    };
    // 列表赋值
    list.value = res.data;
    // 保存总页码
    totalPages = {
      pageSize: Number(res.pageSize),
      pages: Number(res.pages),
      total: Number(res.total),
    }
    if (pages.pageNum < totalPages.pages) {
      pages.pageNum += 1;
    }
    // 数据获取完毕，下拉刷新状态更新
    refreshing.value = false;
    // 数据全部加载完成
    if (list.value.length >= totalPages.total) {
      finished.value = true;
    } else {
      // 如果数据还有未加载部分
      finished.value = false;
    }
  };

  getPatrolInspectDateByMonth();
</script>

<style lang="scss" scoped>
@import "@/assets/universal-list.scss";
.patrolInspect {
}
</style>